package com.lajiaomian.springbootruijiwaimai.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lajiaomian.springbootruijiwaimai.common.BaseContext;
import com.lajiaomian.springbootruijiwaimai.common.R;
import com.lajiaomian.springbootruijiwaimai.pojo.User;
import com.lajiaomian.springbootruijiwaimai.service.impl.UserService;
import com.lajiaomian.springbootruijiwaimai.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.nio.file.Watchable;
import java.util.Map;

/**
 * @author lajiaomian
 * @create 2022-08-16-22:07
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 前台请求发送验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        log.info("手机号：{}",user.toString());
        //先获取手机号
        String phone = user.getPhone();
        //判断手机号是否为空
        if(StringUtils.isNotEmpty(phone)){
            //不为空，生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            log.info("验证码为：{}",code);
            //将验证码保存到session域中
            session.setAttribute(phone,code);
            //返回
            return R.success("验证码发送成功");
        }
        return R.error("手机号为空");
    }

    /**
     * 登录验证
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> checkLogin(@RequestBody Map map,HttpSession session){
        log.info("验证登录:{}",map);
        //获取到验证码后，与域中的存入的进行比较，不正确，就返回
        String phone = (String) map.get("phone");
        String code =(String) map.get("code");
        Integer Scode = (Integer) session.getAttribute(phone);
        String scode = ""+Scode;
        if (!code.equals(scode)){
            return R.error("验证码错误！");
        }

        //先判断数据库中是否有这个用户,有就登录，没有就创建后再登录
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone",phone);
        User user = userService.getOne(wrapper);

        //新建用户，并设置手机号和状态属性
        if(user==null){
            user =new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        //将id设置到域中
        session.setAttribute("user",user.getId());
        return R.success(user);

    }

    /**
     * 登出
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功");
    }

}
